#include "task_core.h"
#include "ostimer.h"

#define MAXNUM_OSTIMER    OSTASK_NUM

static unsigned int cnt_idx = 0;
static unsigned int cntx[MAXNUM_OSTIMER] = {0};
static unsigned int cntx_max[MAXNUM_OSTIMER] = {0};
static unsigned char  timeoutflag[MAXNUM_OSTIMER] = {0};

void ostimer_proc(void)
{
	unsigned int seeki, i;

	for(i=0,seeki=1; i<MAXNUM_OSTIMER; i++,seeki<<=1)
	{
		if(cnt_idx&seeki) 
		{
			cntx[i]++;
			if(cntx_max[i] <= cntx[i])
			{
				timeoutflag[i] = 1;
				cntx[i] = 0;
			}
		}
	}
}

void ostimer_start(TIMERID timerid, unsigned int count)
{
	unsigned int seeki;

	seeki = 0x00000001;
	seeki <<= timerid;

	cntx_max[timerid] = count;
	cntx[timerid] = 0;
	timeoutflag[timerid] = 0;

	cnt_idx |= seeki;
}

void ostimer_clear(TIMERID timerid)
{
	cntx[timerid] = 0;
}

void ostimer_stop(TIMERID timerid)
{
	unsigned int seeki;
	
	seeki = 0x00000001;
	seeki <<= timerid;
	cntx[timerid] = 0;
	timeoutflag[timerid] = 0;
	cnt_idx &= ~seeki;
}

int ostimer_timeout(TIMERID timerid)
{
	if(timeoutflag[timerid])
	{
		timeoutflag[timerid] = 0;
		return 1;
	}

	return 0;	
}
